//
//  LZScanQRCodeViewController.m
//  laziz_Merchant
//
//  Created by xbn_iMac on 2016/12/17.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZScanQRCodeViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UIView+Rotation.h"
#import "UIViewController+InitWithdDefaultNib.h"
#import "LZScanQRCodeFromCameraPresenter.h"
#import "LZOverlayView.h"
#import "LZScanQRCodeFromCrameScanCropAnimationView.h"
#import "LZAlertView.h"
#import "LZCustomerCheckoutViewController.h"
#import "AESCrypt.h"
#import "LZScanQRCodeModel.h"
#import "MJExtension.h"
#import "Masonry.h"

@interface LZScanQRCodeViewController ()

@property (nonatomic, strong) LZScanQRCodeFromCameraPresenter *cameraQRPresenter;

@property (nonatomic, weak) LZScanQRCodeFromCrameScanCropAnimationView *scanAnimationView;
@property (nonatomic, assign) CGRect scanCrop;
@property (nonatomic, assign) float ratio;

@property (nonatomic, strong) UIButton *nav_left_back;

@end

@implementation LZScanQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"结账二维码扫码页面";
    
    self.view.backgroundColor = [UIColor blackColor];
    
    [self initBaseData];
    
    [self createCameraQRCodePresenter];
    
    [self createScanView];
    
    [self configNavigationBar];

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self startSessionAndAnimation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopSessionAndAnimation];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [self stopSessionAndAnimation];
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}


#pragma mark - config data

//配置navi
- (void)configNavigationBar{
    
    self.nav_left_back = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_left_back.frame = CGRectMake(0, 0, 60, 40);
    [self.nav_left_back addTarget:self action:@selector(navbarBackButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"lz_back_en"];
    [self.nav_left_back setImage:image_back forState:UIControlStateNormal];
    self.nav_left_back.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(self.nav_left_back.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self.nav_left_back setLanguageRotaion];
    }
    
    [self hiddenBarNavigationItemSetting:@[self.nav_left_back] type:NAVIGATIONITEMSETTING_LEFT];
    [self lz_setCustomBarAlpha:0];
    
    [self lz_setTitle:LZLocalizedString(@"checkout_scan_coupon", nil)];
    self.titleLabel.alpha = 1;
}

- (void)navbarBackButtonClickAction:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)initBaseData {
    GET_SCREEN_SCALE(scale);
    self.ratio = scale;
    
    if (self.view.frame.size.height>=568) {
        // iPhone5以后
        self.scanCrop = CGRectMake(52*self.ratio, 170*self.ratio, CGRectGetWidth(self.view.frame)-2*52*self.ratio, CGRectGetWidth(self.view.frame)-2*52*self.ratio);
    }
    else
    {
        // iPhone4
        self.scanCrop = CGRectMake(61, 125, CGRectGetWidth(self.view.frame)-2*61, CGRectGetWidth(self.view.frame)-2*61);
    }
}

-(void)createCameraQRCodePresenter {
    
    self.cameraQRPresenter = [[LZScanQRCodeFromCameraPresenter alloc] init];
    
    WS(weakSelf)
    self.cameraQRPresenter.CrameScanResult = ^(NSString* obj, NSError *error){
        __strong __typeof(self) strongSelf = weakSelf;
        
        [strongSelf stopSessionAndAnimation];

        if (error == nil) {
            [strongSelf dealCodeResultWithCode:obj];
        }
        else {
            [strongSelf scanError];
        }
    };
    
    [self.cameraQRPresenter createCameraWithScanCrop:self.scanCrop andBaseView:self.view];
}

#pragma mark - config UI
// 创建中间扫描UI和上边提示的label
-(void)createScanView
{
    [self createScanCropView];
    
    [self createScanAnimationView];
    
    [self createRemindLabel];
}

-(void)createScanCropView {
    // 黑色背景框
    LZOverlayView *scanCropView = [[LZOverlayView alloc] initWithFrame:self.view.bounds andRectDrow:_scanCrop];
    [self.view addSubview:scanCropView];
}

-(void)createScanAnimationView {
    // 中间动画的View
    
    LZScanQRCodeFromCrameScanCropAnimationView *scanAnimationViewTemp = [[LZScanQRCodeFromCrameScanCropAnimationView alloc] initWithFrame:self.scanCrop];
    [self.view addSubview:scanAnimationViewTemp];
    self.scanAnimationView = scanAnimationViewTemp;
}

// 上边提示的view
- (void)createRemindLabel {
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:13];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = UIColorFromRGB(0xcccccc, 1);
    label.text = LZLocalizedString(@"checkout_scan_qrcode_remind", nil);
    [self.view addSubview:label];
    
    GET_SCREEN_SCALE(scale)
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(80*scale);
        make.leading.equalTo(self.view).offset(75*scale);
        make.trailing.equalTo(self.view).offset(-75*scale);
    }];
}


#pragma mark - event 

-(void)startSessionAndAnimation {
    [self.cameraQRPresenter sessionStart];
    [self.scanAnimationView startLineAnimation];
}

-(void)stopSessionAndAnimation {
    [self.cameraQRPresenter sessionStop];
    [self.scanAnimationView stopLineAnimation];
}

-(void)dealCodeResultWithCode:(NSString*)code
{
    // 对扫除的数据进行aes解密
    NSString *decryptedData = [AESCrypt decrypt:code password:@"xbnlazizqrcodepassword1234"];
//    DLog(@"%@",decryptedData);
    if (decryptedData) {
        LZScanQRCodeModel *model = [LZScanQRCodeModel mj_objectWithKeyValues:decryptedData];
        if (model == nil) {
            [self scanError];
        }
        else {
            // 扫描成功
            DLog(@"lalalallalallalala");
            LZCustomerCheckoutViewController *vc = [[LZCustomerCheckoutViewController alloc] initWithDefaultNib];
            vc.scanModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    else {
        [self scanError];
    }
}

#pragma mark - 二维码无效
-(void)scanError {
    
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"checkout_scan_error_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"checkout_scan_again", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        DLog(@"恩，确实点击了第%ld个按钮",(long)index);
        if (weakSelf) {
            [weakSelf startSessionAndAnimation];
        }
    };
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(error) {
        DLog(@"json解析失败：%@",error);
        return nil;
    }
    
    return dic;
}

@end
